<template>
  <div class="app-container"> 
      <div class="query-wrapper" model="queryParams">
        <el-select v-model="queryParams.vesselName" filterable clearable placeholder="Vessel" @change="selectVessel" style="width:180px">
          <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
          </el-option>
        </el-select>
        &nbsp;&nbsp;
        <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="Voyage" style="width:100px" >
          <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
          </el-option>
        </el-select>
        &nbsp;&nbsp;
        <el-input v-model="queryParams.name" clearable  style="width:200px" placeholder="Brand Name"/>
         &nbsp;&nbsp;      
        <el-button type="primary"  icon="search"  @click="search">{{
          $t("ship.button.search")
        }}</el-button>
         <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>  
        <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <el-button type="primary" plain icon="plus" @click="addClickEvent" v-hasPermi="['brandInException:edit']">
          {{ $t("ship.button.plus") }}
        </el-button> 
    </div>
  </div>

  <el-table stripe class="daf-table" :data="listData"  :cell-style="{textAlign:'center'}"  style="width: 100%"  >
    <!-- <el-table-column prop="portId" label="Port No" width="120" /> -->
    <!-- <el-table-column prop="id" label="ID" />  -->
    <el-table-column prop="vesselName" label="Vessel Name" /> 
    <el-table-column prop="voyageNo" label="Voyage" /> 
    <el-table-column prop="brand" label="Brand" /> 
    <el-table-column prop="remark" label=" " />
 
    <el-table-column label="Operation" width="120" v-hasPermi="['brandInException:edit']">
      <template #default="scope">
        <span class="btn-primary"  @click="editClickEvent(scope.row)">{{
          $t("ship.button.edit")
        }}</span
        >&nbsp;&nbsp;
        <span class="btn-primary"  @click="removeClickEvent(scope.row.id)">{{
          $t("ship.button.remove")
        }}</span>
      </template>
    </el-table-column>
  </el-table>

  <pagination
    v-show="total > 0"
    :total="total"
    :page="queryParams.pageNum"
    :limit="queryParams.pageSize"
    @pagination="pageQuery"
    style="float: right"
  />

  <el-dialog
    :width="400" 
    destroy-on-close
    draggable
    :title="dialogTitle"
    v-model="dialogFormVisible"
  >
    <el-form :model="formParam" :rules="rules" ref="custForm">    
      <el-row>
        <el-col :span="24">
          <el-form-item label="Vessel Name" label-width="120px" prop="vesselName">
            <el-select
                v-model="formParam.vesselName"
                filterable
                placeholder="choose vessel"
                width="200"
                @change="selectVessel" >
                <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
                </el-option>
              </el-select> 
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="Voyage No" label-width="120px" prop="voyageNo">
            <el-select v-model="formParam.voyageNo" filterable placeholder="choose voyage" >
              <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="Brand" label-width="120px" prop="brand">
          <el-select v-model="formParam.brand" filterable allow-create placeholder="choose brand">
            <el-option :key="item.name" :label="item.name" :value="item.name" v-for="item in brands">
            </el-option>
          </el-select>
          </el-form-item>
        </el-col>
      </el-row>     
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
        }}</el-button>
        
        <el-button type="primary" @click="submitForm">{{
          $t("ship.button.submit")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup name="brandInException">
// @ts-nocheck
import { ref, onMounted, reactive, watch } from "vue";
import service from "@/utils/request";
import useDataMapStore from '@/store/modules/dataMap'
import { ElNotification, ElMessageBox } from "element-plus";
const router = useRouter();
const custForm = ref();
const dialogTitle = ref("");

let vessels = reactive([])
let voyages = reactive([])
let brands = reactive([])


const selectVessel = value => { 
  voyages = []
  queryParams.voyageNo = null 
  voyages = (vessels.find(item => item.vesselName == value) || { schedules: [] }).schedules;  
};
 
const initForm = {
  id:'',
  vesselName: '',
  voyageNo: '',
  brand: ''
};
let isAdd = false
const addClickEvent = () => {
  dialogTitle.value = "Add Brand In Exception";
  isAdd = true;
  dialogFormVisible.value = true;
  Object.assign(formParam, initForm);
};

const editClickEvent = (row: any) => {
  dialogTitle.value = "Update Brand In Exception";
  dialogFormVisible.value = true;
  isAdd = false;
  Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
};

const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  vesselName: null, 
  orderByColumn: undefined,
  isAsc: undefined,
});

const search = ()=>{
  refreshTable()
}
const total = ref(0);
const formParam = reactive(Object.assign({}, initForm));

const dialogFormVisible = ref(false);
const rules = ref({
  vesselName: [{ required: true, message: "Vessel Name can't be blank" }],
  voyageNo:[{ required: true, message: "Voyage can't be blank" }],
  brand: [{ required: true, message: "brand can't be blank" }] 
});

const listData = ref([]);
const refreshTable = async () => {
  let result = await service.get("/shipping/freightRule/getTable", { params: queryParams });
  listData.value = result.data;
  total.value = result.total;
};

const resetQuery = (data) => {
    Object.assign(queryParams, data)
    listData.value = []
    total.value = 0
}
const pageQuery = async (e) => {
    queryParams.pageNum = e.page;
    queryParams.pageSize = e.limit;
    refreshTable();
  };

const resetForm = () => {
  // @ts-ignore
  custForm.value.resetFields();
};

const submitForm = () => {
  // @ts-ignore
  custForm.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
      await service[isAdd ? "post" : "put"]("shipping/freightRule", formParam);

    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right",
    });
    dialogFormVisible.value = false;
    refreshTable();
  });
};


const removeClickEvent = id => {
  ElMessageBox.confirm("Confirm to delete the data？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel"
  }).then(async () => {
    await service.delete(`shipping/freightRule/${id}`);
    refreshTable();
    // @ts-ignore
    ElNotification.success({ title: "Prompt information", message: "Delete successfully!", position: "bottom-right" });
  });
};

const brandList = ref([])
 
onMounted(async () => {       
  await service.get("/shipping/vessel/getSchedule").then(resp=>{
    vessels = resp.data
  }) 
   
  let result = await service.get("/shipping/brand/list");
  if (result) {
      brands = result.data;
  }
  refreshTable()

});
</script>
<style lang="scss" scoped>
  // .app-container {
  //   width: 800px;
  //   margin: 10px;
  // }

  .dialog-footer {
    margin-top: 80px;
    display: flex;
    justify-content: center;
  }
</style>